package com.audio.record;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 语音录制对象
 *
 * @author sam
 */
public class AudioRecorder extends Thread {

    // 麦克风
    private static TargetDataLine mic;

    private String audioName;

    public AudioRecorder(String audioName) {
        this.audioName = audioName;
    }

    /**
     * 执行方法
     */
    @Override
    public void run() {
        initRecording();
        statRecording();
    }

    /**
     * 开始录音
     */
    public void initRecording() {
        System.out.println("开始录音...");
        try {
            AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                    44100, 16, 2, 4, 4410, false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);

            mic = (TargetDataLine) AudioSystem.getLine(info);
            mic.open();

            System.out.println("正在录音...");
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存录音
     */
    public void statRecording() {
        try {
            mic.start();
            AudioInputStream audioInputStream = new AudioInputStream(mic);
            File file = new File(audioName);
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, file);
            System.out.println("录音文件保存...");
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 停止录音
     */
    public void stopRecording() {
        mic.stop();
        mic.close();
        System.out.println("录音结束...");
    }

    /**
     * 播放录音
     *
     * @param file 文件地址
     */
    public void play(String file) {
        try {
            System.out.println("开始播放...");
            FileInputStream fis = new FileInputStream(file);
            AudioFormat.Encoding encoding = new AudioFormat.Encoding("PCM_SIGNED");
            // 编码格式，采样率，每个样本的位数，声道，帧长（字节），帧数，是否按big-endian字节顺序存储
            AudioFormat format = new AudioFormat(encoding,
                    44100, 16, 2, 4, 44100, false);
            SourceDataLine auline = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            try {
                auline = (SourceDataLine) AudioSystem.getLine(info);
                auline.open(format);
            } catch (Exception e) {
                e.printStackTrace();
            }

            auline.start();
            byte[] b = new byte[256];
            try {
                while (fis.read(b) > 0) {
                    auline.write(b, 0, b.length);
                }
                auline.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
